import { sys } from "cc";

interface UserData {
    name: string;
    level: number;
    gold: number;
    flag: boolean;
    LeveLStar:number []
}

export class UserDataInfo implements UserData {
    name: string;
    level: number;
    gold: number;
    flag: boolean;
    LeveLStar: number[]

    private static instance: UserDataInfo | null = null;

    // 构造函数私有化，防止外部直接创建实例
    private constructor() {
        this.name = "Default User";
        this.level = 1;
        this.gold = 0;
        this.flag = false;
        this.LeveLStar = [0]
    }

    // 获取单例实例的静态方法
    public static getInstance(): UserDataInfo {
        if (this.instance === null) {
            this.instance = new UserDataInfo();
        }
        return this.instance;
    }

    // 可以添加其他方法来更新或者操作数据
    updateUser(name: string, level: number, gold: number, flag: boolean ,LeveLStar:number[]): void {
        this.name = name;
        this.level = level;
        this.gold = gold;
        this.flag = flag;
        this.LeveLStar = LeveLStar
    }

    public setLevelStarAt(index: number, value: number): void {
        // 如果索引已经存在
        if (index < this.LeveLStar.length) {
            // 只有在新值大于原值时才进行修改
            if (value > this.LeveLStar[index]) {
                this.LeveLStar[index] = value;
            }
        } else {
            // 如果索引不存在，填充数组并添加新值
            this.LeveLStar.length = index;  // 扩展数组的长度
            this.LeveLStar[index] = value;  // 添加新值
        }
    }


    public static loadUserData(){
        const jsonStr = sys.localStorage.getItem('userData');
        const userData = JSON.parse(jsonStr) as UserData;
        console.log('单例中',userData)
        return userData as UserData
    }




    public static saveUserData(userData:UserData){
        
        let user = UserDataInfo.getInstance()
        user.name = userData.name;
        user.gold = userData.gold;
        user.level = userData.level
        user.LeveLStar = userData.LeveLStar

        const jsonStr = JSON.stringify(userData);
        sys.localStorage.setItem('userData',jsonStr);
    }


    public static sumArray(arr: number[]): number {
        return arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
    }


    
}




